using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using static GPTSoVITSTextToSpeech;

public class GPTSoVITSFASTAPI : TTS
{
    #region 配置参数


    [Header("参考音频路径(GPT-SoVITS项目中的本地路径)")]
    [SerializeField] private string m_ReferWavPath = string.Empty; // 参考音频路径

    [Header("参考音频所对应的文本")]
    [SerializeField] private string m_ReferenceText = ""; // 参考文本内容

    [Header("参考文本语言类型")]
    [SerializeField] private Language m_ReferenceTextLan = Language.中文; // 原始音频语言

    [Header("合成目标语言类型")]
    [SerializeField] private Language m_TargetTextLan = Language.中文; // 合成语音语言

    #endregion

    /// <summary>           
    /// 调用语音合成：传入文本，回调返回音频
    /// </summary>
    /// <param name="_msg">要合成的文本</param>
    /// <param name="_callback">合成完成后的回调</param>
    public override void Speak(string _msg, Action<AudioClip, string> _callback)
    {
        StartCoroutine(GetVoice(_msg, _callback));
    }

    /// <summary>
    /// 语音合成核心协程
    /// </summary>
    /// <param name="_msg">要合成的文本</param>
    /// <param name="_callback">回调</param>
    /// <returns>返回 AudioClip</returns>
    private IEnumerator GetVoice(string _msg, Action<AudioClip, string> _callback)
    {
        stopwatch.Restart();

        // 构造请求参数
        RequestData _requestData = new RequestData
        {
            refer_wav_path = m_ReferWavPath,
            prompt_text = m_ReferenceText,
            prompt_language = m_ReferenceTextLan.ToString(),
            text = _msg,
            text_language = m_TargetTextLan.ToString()
        };

        // 序列化为 JSON
        string _postJson = JsonUtility.ToJson(_requestData);

        // 发送 POST 请求
        using (UnityWebRequest request = new UnityWebRequest(m_PostURL, "POST"))
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(_postJson);
            request.uploadHandler = new UploadHandlerRaw(data);
            request.downloadHandler = new DownloadHandlerAudioClip(m_PostURL, AudioType.WAV);
            request.SetRequestHeader("Content-Type", "application/json");

            yield return request.SendWebRequest();

            if (request.responseCode == 200)
            {
                AudioClip audioClip = ((DownloadHandlerAudioClip)request.downloadHandler).audioClip;
                _callback(audioClip, _msg);
            }
            else
            {
                Debug.LogError("语音合成失败: " + request.error);
            }
        }
    }

    #region 数据结构

    [Serializable]
    public class RequestData
    {
        public string refer_wav_path = string.Empty;    // 参考音频路径
        public string prompt_text = string.Empty;       // 参考音频的文本
        public string prompt_language = string.Empty;   // 参考语言
        public string text = string.Empty;              // 要合成的目标文本
        public string text_language = string.Empty;     // 合成语言
    }

    #endregion
}